package co.fitstart.mobile.web.controller.course;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.support.Result;
import com.demo2do.core.utils.DateUtils;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.wechat.web.interceptor.WechatJsConfig;

import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.user.User;
import co.fitstart.entity.user.bwh.BwhRecord;
import co.fitstart.mobile.service.CourseRoundService;
import co.fitstart.mobile.service.UserService;
import co.fitstart.mobile.web.interceptor.MobileDetect;
import co.fitstart.mobile.web.interceptor.Router;
import co.fitstart.mobile.web.interceptor.WechatAuthority;
import co.fitstart.mobile.web.resolver.Secure;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("/profile/courses/{courseId}/bmr-records")
public class CourseBmrController {
    
    private static final Logger logger = LoggerFactory.getLogger(CourseBmrController.class);
    
    @Autowired
    private CourseRoundService courseRoundService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 
     * @param user
     * @param courseRoundId
     * @return
     */
    @RequestMapping("")
    @Router(targetUrl = "/required-wechat")
    @WechatAuthority
    @MobileDetect
    @WechatJsConfig
    public ModelAndView index(@Secure User user,
                              @PathVariable("courseId") Long courseRoundId) {
        
        ModelAndView modelAndView = new ModelAndView("/course/bwh/bwh-record-list");
        
        CourseRound courseRound = courseRoundService.loadCourseRound(courseRoundId);
        List<BwhRecord> bwhRecords = userService.listBwhRecords(user, courseRound);
        boolean couldRecord = true;
        
        if(bwhRecords != null && bwhRecords.size() > 0 && DateUtils.isSameWeek(bwhRecords.get(0).getCreateTime(), new Date())) {
            couldRecord = false;
        }
        
        modelAndView.addObject("bwhRecords", bwhRecords);
        modelAndView.addObject("courseRound", courseRound);
        modelAndView.addObject("couldRecord", couldRecord);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    @Router(targetUrl = "/required-wechat")
    @WechatJsConfig
    public ModelAndView create(@PathVariable("courseId") Long courseRoundId) {
        ModelAndView modelAndView = new ModelAndView("/course/bwh/bwh-record-create");
        
        modelAndView.addObject("courseId", courseRoundId);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param user
     * @param courseRoundId
     * @param bwhRecord
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.PATCH)
    @Router(targetUrl = "/required-wechat")
    @WechatAuthority
    @MobileDetect
    @WechatJsConfig
    public @ResponseBody String onCreate(@Secure User user,
                               @PathVariable("courseId") Long courseRoundId,
                               BwhRecord bwhRecord) {
        Result result = new Result();
        
        try {
            CourseRound courseRound = courseRoundService.loadCourseRound(courseRoundId);
            
            if(courseRound == null || (courseRound.getStudent().getUser() != user)) {
                result.fail().message("添加三围记录失败");
            } else {
                List<BwhRecord> bwhRecords = userService.listBwhRecords(user, courseRound);
                if(bwhRecords != null && bwhRecords.size() > 0 && DateUtils.isSameWeek(bwhRecords.get(0).getCreateTime(), new Date())) {
                    result.fail().message("添加失败，一周只能记录一次三围数据");
                } else {
                    courseRoundService.createbwhRecord(bwhRecord, courseRound);
                    result.success().message("添加三围记录成功");
                }
            }
        } catch (Exception e) {
            logger.error("#onCreateBmrRecord() bmr record error", e);
            result.fail().message("添加三围记录失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
}
